<!--  -->
<template>
  <div class="userStyle">
    <!-- 搜索 -->
    <div class="formSearch">
      <el-form :inline="true" :model="formInline">
        <el-form-item label="用户名">
          <el-input v-model="formInline.search" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="是否启用">
          <el-select v-model="formInline.state" placeholder="请选择">
            <el-option label="是" value="1" />
            <el-option label="否" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" plain @click="search">查询</el-button>
          <el-button type="success" plain @click="add">新增用户</el-button>
          <el-button type="info" plain @click="clear">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 表格 -->
    <div class="tableBox">
      <el-table ref="multipleTable" :data="tableData" border
        :header-cell-style="{ background: '#EEF3FF', color: '#333333' }" tooltip-effect="dark" style="width: 100%">
        <el-table-column label="用户名" width="220">
          <template slot-scope="scope">{{ scope.row.username }}</template>
        </el-table-column>
        <el-table-column prop="name" label="姓名" />
        <el-table-column prop="sex" label="性别" width="80" />
        <el-table-column prop="phone" label="电话" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="state" label="是否启用">
          <template slot-scope="scope">
            <span v-if="scope.row.state == 0">停用</span>
            <span v-if="scope.row.state == 1">启用</span>
          </template>
        </el-table-column>
        <el-table-column prop="shopTypes" label="商家类型" />
        <el-table-column prop="roleNames" label="用户角色" />
        <el-table-column prop="createTime" label="创建时间" />
        <el-table-column label="操作" show-overflow-tooltip>
          <template slot-scope="scope">
            <div class="btnList">
              <el-button type="text" @click="edit(scope.row)">编辑</el-button>
              <el-button type="text" @click="del(scope.row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="fenye">
        <el-pagination :current-page="currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="10"
          layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </div>

    <!-- *************对话框开始************* -->
    <el-dialog :title="userState ? '新增用户' : '修改用户'" :visible.sync="addFormDialog" width="30%" center
      :close-on-click-modal="false">
      <!-- 新增用户 -->
      <div>
        <el-form ref="ruleForm" :model="addForm" label-width="80px" :rules="userRules">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addForm.username" placeholder="请输入用户名" />
          </el-form-item>
          <el-form-item label="姓名" prop="name">
            <el-input v-model="addForm.name" placeholder="请输入姓名" />
          </el-form-item>
          <el-form-item label="手机号">
            <el-input v-if="phoneShow" :value="hidden(addForm.phone, 3, 4)" placeholder="请输入手机号"
              @focus="focusPhoneInput" />
            <el-input v-if="!phoneShow" ref="phoneCls" v-model="addForm.phone" clearable placeholder="请输入手机号"
              @change="changePhoneInput" />
            <!-- <div @click="inputPhone" v-else class="newPhone">
              <span>{{ hidePhone(addForm.phone) }}</span>
            </div> -->
          </el-form-item>
          <el-form-item label="密码">
            <el-input v-model="addForm.password" placeholder="请输入密码" show-password />
          </el-form-item>
          <el-form-item label="邮箱">
            <el-input v-if="emailShow" ref="emailCls" :value="hidden(addForm.email, 3, 4)" placeholder="请输入邮箱"
              @focus="focusEmailInput" />
            <el-input v-else ref="phoneCls" v-model="addForm.email" clearable placeholder="请输入邮箱"
              @change="changeEmailInput" />
            <!-- <el-input v-model="addForm.email" placeholder="请输入邮箱" /> -->
          </el-form-item>
          <el-form-item label="性别">
            <el-radio-group v-model="addForm.sex">
              <el-radio label="男" />
              <el-radio label="女" />
            </el-radio-group>
          </el-form-item>
          <el-form-item label="是否启用">
            <el-select v-model="addForm.state" placeholder="请选择">
              <el-option label="是" :value="1" />
              <el-option label="否" :value="0" />
            </el-select>
          </el-form-item>
          <el-form-item label="选择角色">
            <el-select v-model="addForm.roleIds" multiple placeholder="请选择" @remove-tag="removeTag" @change="tagChange">
              <el-option v-for="item in roleList" :key="item.roleId" :label="item.roleName" :value="item.roleId" />
            </el-select>
          </el-form-item>
          <el-form-item label="所属行业">
            <el-select v-model="addForm.userTypeId" multiple placeholder="请选择" @remove-tag="removeType"
              @change="typeChange">
              <el-option v-for="item in typeList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="商家类型">
            <el-select v-model="addForm.shopTypeId" multiple placeholder="请选择" @remove-tag="removeShopType"
              @change="shopTypeChange">
              <el-option v-for="item in shopTypeList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="简介">
            <el-input v-model="addForm.brief" type="textarea" placeholder="请输入简介" />
          </el-form-item>
          <el-form-item label="头像">
            <el-upload class="avatar-uploader" :action="action" :headers="myHeaders" :show-file-list="false"
              :on-success="(res) => { handleAvatarSuccess(res, 'avatar') }">
              <img v-if="addForm.avatar" :src="addForm.avatar" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon" />
            </el-upload>
            <el-input v-model="addForm.avatar" style="margin-top:20px;" placeholder="请输入图片地址" />
            <span class="tips">请上传图片或输入图片地址</span>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addFormDialog = false">取 消</el-button>
        <el-button type="primary" @click="addForm_enter('ruleForm')">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { uploadUrl, token } from '@/utils/request'
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// 例如：import 《组件名称》 from '《组件路径》';
import {
  getList,
  userAdd,
  roleGetall,
  userGetById,
  userUpdate,
  userDelete,
  setupTypeList,
  getShopTypeList
} from '@/api/setup'
const PhoneRule = /^1(3\d|4[5-9]|5[0-35-9]|6[567]|7[0-8]|8\d|9[0-35-9])\d{8}$/
export default {
  // import引入的组件需要注入到对象中才能使用
  components: {},
  data () {
    // 这里存放数据
    return {
      action: uploadUrl,
      myHeaders: {
        'Authorization-admin': token
      },
      formInline: {
        search: '', // 搜索字段
        state: '', // 是否启用 1-是 0-否
        page: '1', // 当前页
        pageSize: '10' // 每页记录数
      },
      total: 1,
      tableData: [],
      currentPage: 1,
      userState: 1,
      addForm: {
        name: '', // 昵称
        phone: '', // 电话
        password: '', // 密码
        email: '', // 邮箱
        sex: '男', // 性别
        state: 1, // 是否启用 1-是 0-否
        roleIds: [], // 角色id
        userTypeId: [],
        shopTypeId:[],//商家类型id
        brief: '',
        avatar: ''
      },
      addFormDialog: false,
      userRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        name: [{ required: true, message: '请输入姓名', trigger: 'blur' }]
      },
      roleList: [],
      typeList: [],
      shopTypeList: [],//商家类型列表
      newPhone: '',
      showPhone: false,
      shopInfo: {},
      privacyTime: 0,
      phoneShow: true, // 显示脱敏手机号
      emailShow: true, // 显示脱敏邮箱
    }
  },
  // 监听属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {},
  // 生命周期 - 创建完成（可以访问当前this实例）
  created () { },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted () {
    this.getAll(this.formInline)
    this.privacyTime = localStorage.getItem('privacyTime');
  },
  // 方法集合
  methods: {
    // 图片上传回调
    handleAvatarSuccess (response, key) {
      const { url } = response.data
      this.addForm[key] = url
      this.$forceUpdate()
    },
    focusEmailInput () {
      this.emailShow = false
      this.addForm.email = ''
      // 自动获取焦点
      this.$nextTick(() => {
        this.$refs.emailCls.focus()
      })
    },
    changeEmailInput () { },
    focusPhoneInput () {
      this.phoneShow = false
      this.addForm.phone = ''
      // 自动获取焦点
      this.$nextTick(() => {
        this.$refs.phoneCls.focus()
      })
    },
    changePhoneInput () {
      this.checkPhone()
    },
    // 检查手机号
    checkPhone () {
      if (this.addForm.phone !== '' && !PhoneRule.test(this.addForm.phone)) {
        return this.$message.warning('请输入正确手机号');
      }
    },
    handleSizeChange (val) {
      this.formInline.pageSize = val
      this.getAll(this.formInline)
    },
    handleCurrentChange (val) {
      this.formInline.page = val
      this.getAll(this.formInline)
    },
    removeTag (index) {
      console.log(index)
    },
    tagChange (index) {
      this.$forceUpdate()
      console.log(index)
    },
    removeType (index) {
      console.log(index)
    },
    typeChange (index) {
      this.$forceUpdate()
      console.log(index)
    },
    removeShopType (index) {
      console.log(index)
    },
    shopTypeChange (index) {
      this.$forceUpdate()
      console.log(index)
    },
    // 查询
    search () {
      this.total = 1
      this.formInline.page = 1
      this.getAll(this.formInline)
    },
    // 清除
    clear () {
      this.formInline = {
        search: '', // 搜索字段
        state: '', // 是否启用 1-是 0-否
        page: '1', // 当前页
        pageSize: '10' // 每页记录数
      }
      this.getAll(this.formInline)
    },
    // 新增用户
    add () {
      this.userState = 1
      this.addFormDialog = true
      this.showPhone = true
      this.addForm = {
        name: '', // 昵称
        phone: '', // 电话
        password: '', // 密码
        email: '', // 邮箱
        sex: '男', // 性别
        state: 1, // 是否启用 1-是 0-否
        roleIds: [], // 角色id
        userTypeId: [], // 行业id
        shopTypeId:[],//商家类型id
        brief: '',
        avatar: ''
      }
    },
    // 确认新增用户
    addForm_enter (ruleForm) {
      console.log(this.addForm, 'this.addForm')
      this.$refs[ruleForm].validate(valid => {
        if (valid) {
          // 检查手机号码是否正确
          if (this.checkPhone()) {
            return
          }
          if (Object.prototype.toString.call(this.addForm.userTypeId) === '[object Array]') {
            this.addForm.userTypeId = this.addForm.userTypeId.filter((item) => {
              return item !== null && typeof item !== 'undefined' && item !== '';
            }).join(',')
          }
          if (Object.prototype.toString.call(this.addForm.shopTypeId) === '[object Array]') {
            this.addForm.shopTypeId = this.addForm.shopTypeId.filter((item) => {
              return item !== null && typeof item !== 'undefined' && item !== '';
            }).join(',')
          }
          if (this.userState) {
            userAdd(this.addForm).then(res => {
              console.log(res)
              if (res.code === '') {
                this.$message({
                  message: '新增成功',
                  type: 'success'
                })
              }
              this.getAll(this.formInline)
              this.addFormDialog = false
            })
          } else {
            userUpdate(this.addForm).then(res => {
              console.log(res)
              if (res.code === '') {
                this.$message({
                  message: '修改成功',
                  type: 'success'
                })
              }
              this.getAll(this.formInline)
              this.addFormDialog = false
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 编辑用户
    edit (row) {
      this.userState = 0
      this.addFormDialog = true
      this.showPhone = false
      this.phoneShow = true
      this.emailShow = true
      console.log(row)
      userGetById({ platformUserId: row.platformUserId }).then(res => {
        this.addForm = res.data
        this.addForm.roleIds = res.data.ids
        console.log(this.addForm.userTypeId)
        if (this.addForm.userTypeId == null || this.addForm.userTypeId === 'undefined' || this.addForm.userTypeId === '') {
          this.addForm.userTypeId = []
        } else {
          this.addForm.userTypeId = this.addForm.userTypeId.split(',').filter((item) => {
            return item !== null && typeof item !== 'undefined' && item !== '';
          }).map(Number);
        }

        console.log(this.addForm)
        console.log(this.roleList)
        // this.addForm.roleIds = [1];
      })
    },
    // 删除用户
    async del (row) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          userDelete({ platformUserId: row.platformUserId }).then(res => {
            if (res.code === '') {
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
            }
            this.getAll(this.formInline)
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 初始化查询所有数据
    async getAll (formInline) {
      const res = await getList(formInline)
      // const res2 = await roleGetall({ search: '', page: 1, pageSize: 100 })
      // const res3 = await setupTypeList({ name: '', page: 1, pageSize: 100 })
      this.tableData = res.data.list
      this.total = res.data.total
      // this.roleList = res2.data.list
      // this.typeList = res3.data.list
      this.getType()
    },
    async getType () {
      const res2 = await roleGetall({ search: '', page: 1, pageSize: 100 })
      const res3 = await setupTypeList({ name: '', page: 1, pageSize: 100 })
      const res4 = await getShopTypeList({ name: '', page: 0, pageSize: 0 })
      console.log('res4', res4)
      this.roleList = res2.data.list
      this.typeList = res3.data.list
      this.shopTypeList = res4.data.list
    },

    // 隐藏中间号码
    hidePhone (phone) {
      // const reg = /^(\d{3})\d{4}(\d{4})$/
      // phone = phone.replace(reg, '$1****$2')
      return phone
    },
    // 中间部分
    hidden (str, frontLen, endLen) {
      let endLenData = 0
      if (str && str.length !== 2) {
        endLenData = endLen
      }
      const len = str.length - frontLen - endLenData;
      let xing = '';
      for (let i = 0; i < len; i++) {
        xing += '*';
      }
      return (
        str.substring(0, frontLen) + xing + str.substring(str.length - endLenData)
      );
    },
    inputPhone () {
      this.showPhone = true
      this.newPhone = ''
      this.$nextTick(() => {
        this.$refs.phoneCls.focus()
      })
    }
  }
}
</script>
<style lang='scss' scoped>
//@import url(); 引入公共css类
@import url("../../../styles/elDialog.scss");

.userStyle {
  padding: 20px;

  .newPhone {
    width: 100%;
    height: 40px;
    line-height: 40px;
    padding: 0 15px;
    border-radius: 4px;
    border: 1px solid #DCDFE6;
    cursor: text;
  }
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 100px;
  height: 100px;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
  border: 1px dashed #d9d9d9;
}

.avatar {
  width: 100px;
  height: auto;
  display: block;
}
</style>
